import { XCells, XFloatRowsInfo, XRowsInfo, XSheet } from "@/ts/base/schema";
import { RefGraph } from "..";
import { NodeRef, ReportFloatColumnRef } from "../ref/refs";
import { GraphNodeBase } from "./GraphNodeBase";
import { IFormDataHost } from "../../types/service";
import { getSubData } from "@/components/DataStandard/NewReportForm/Utils";
import RefParser from "../ref/RefParser";

export default class ReportFloatColumnRefNode extends GraphNodeBase<'report-float-column'> {
  get name() {
    const suffix = this.ref.inline ? '-inline' : '';
    return `${this.ref.floatRow}$${this.ref.column}${suffix}`;
  }
  get label() {
    return `[浮动行列] ${this.ref.sheet} ${this.ref.floatRow} ${this.ref.column}列`;
  }

  refs: NodeRef[] = [];
  
  get value() {
    // const form = this.model.formData.primary[this.ref.formId] || {};
    // const data = getSubData(this.floatRow, form);
    const data = this.model.formData.report[this.ref.floatRow] as any[];
    return data.map(d => d[this.ref.column]);
  }
  set value(_: any) {
    throw new Error('无法修改浮动行列引用');
  }

  readonly ref: ReportFloatColumnRef;
  readonly model: IFormDataHost;
  readonly graph: RefGraph;

  readonly floatRowKey: string;
  readonly floatRow: XFloatRowsInfo;
  readonly column: XRowsInfo;
  readonly formId: string;
  needCalculate = false;
  expression = '';

  constructor(ref: ReportFloatColumnRef, graph: RefGraph, model: IFormDataHost) {
    super('report-float-column');
    this.ref = ref;
    this.model = model;
    this.graph = graph;

    const sheet = graph.service.formInfo[ref.sheet];
    if (!sheet || sheet.typeName !== '工作表') {
      throw new ReferenceError(`表 ${ref.sheet} 不存在！`);
    }

    const floatRows = sheet.form.sheetConfig.floatRowsSetting || [];
    const floatRow = floatRows.find(f => f.floatRowCode == ref.floatRow);
    if (!floatRow) {
      throw new ReferenceError(`浮动行 ${ref.floatRow} 不存在！`);
    }
    const column = floatRow.rowsInfo.find(c => c.name == ref.column);
    if (!column) {
      throw new ReferenceError(`浮动行 ${ref.floatRow} 中不存在列 ${ref.column}`);
    }

    this.floatRowKey = floatRow.attributeId!;
    this.floatRow = floatRow;
    this.column = column;
    this.formId = sheet.reportId!;
    
    this.parseRef();
  }

  protected parseRef() {
    if (!this.ref.inline) {
      return;
    }

    if (this.column.rule.value?.type === '函数型') {
      this.expression = this.column.rule.value.valueString;
      this.needCalculate = true;
    } else {
      return;
    }

    const refs = RefParser.columnRefs(this.expression);
    for (const ref of refs.columns) {
      this.refs.push({
        type: 'report-float-column',
        name: `${this.ref.floatRow}$${ref}-inline`,
        formId: this.formId,
        sheet: this.ref.sheet,
        floatRow: this.ref.floatRow,
        column: ref,
        inline: true,
      });
    }
  }
}